<script setup>
  import { ref, reactive, toRaw, computed, onMounted, watch } from 'vue'
  const teamInfoItem = { // 队长信息
    name: '',
    // 性别
    gender: '',
    // 微信号
    wechat: '',
    // 邮箱
    email: '',
    // 高校名称
    school: '',
    // 专业名称
    major: '',
    // 年级
    grade: '',
  }
  const teacherItem = { // 指导老师信息
    // 姓名
    name: '',
    // 性别
    gender: '',
    // 手机号
    phone: '',
    // 邮箱
    email: '',
    // 高校名称
    school: '',
    // 职业名称
    job: '',
  }
  // 团队队员信息
  const teamMemberItem = {
    // 姓名
    name: '',
    // 性别
    gender: '',
    // 手机号
    phone: '',
    // 邮箱
    email: '',
    // 高校名称
    school: '',
    // 专业名称
    major: '',
    // 年级
    grade: '',
  }


  const formData = reactive({
    agree: '', // 是否同意
    type: '', // 团队想要参加的类型 [1 花旗挑战 0 自选赛道]
    teamType: '', // 哪种 [1 ESG（环境、社会与公司治理） 2 VE（虚拟经济）]
    esgName: '', // ESG 项目名称
    vEName: '', // Vitual Economy项目名称
    projectName: '', // 项目名称
    teamName: '', // 团队名称
    teamPhone: '', // 团队队长手机号
    teamInfo: [
      { ...teamInfoItem },
    ],
    // 指导老师信息
    teacher: [
      { ...teacherItem }
    ],
    // 团队队员
    teamMember: [
      { ...teamMemberItem },
      { ...teamMemberItem },
    ]
  })

  function addTeacher() {
    formData.teacher.push({ ...teacherItem })
  }

  function addTamMember() {
    formData.teamMember.push({ ...teamMemberItem })
  }

  // 本地缓存
  watch(formData, (n) => {
    localStorage.setItem('formDataStore__HQB', JSON.stringify(n))
  })

  const formRef = ref(null)
  const rawForm = toRaw(formData)
  const csrf_token = window.csrf_token
  const formAction = window.formAction
  const formDefaultData = window.formDefaultData



  function submit() {
    if (!checkForm()) {
      return
    }
    formRef.value.submit()
  }

  onMounted(() => {
    if (formDefaultData) {
      Object.assign(formData, JSON.parse(formDefaultData))
      return
    }
    const _formDataStore = localStorage.getItem('formDataStore__HQB')
    const formDataJson = JSON.parse(_formDataStore)
    if (_formDataStore) {
      if (confirm('你已经填写了部分信息,是否继续填写?')) {
        Object.assign(formData, formDataJson)
      }
    }
  })

  function checkForm() {

    if (formData.agree === '') {
      alert('请确认是否同意本次大赛及授权')
      return false
    }
    if (formData.type === '') {
      alert('请选择你们团队想要参加的类型')
      return false
    }

    if (formData.type == '1' && formData.teamType === '') {
      alert('请选择要参加的挑战')
      return false
    }
    if (formData.type == '1' && formData.teamType == '1' && formData.esgName === '') {
      alert('请填写ESG项目名称')
      return false
    }
    if (formData.type == '1' && formData.teamType == '0' && formData.vEName === '') {
      alert('请填写Vitual Economy项目名称')
      return false
    }
    if (formData.type == '0' && formData.projectName === '') {
      alert('请填写项目名称')
      return false
    }

    if (formData.teamName === '') {
      alert('请选择你们的团队名称')
      return false
    }
    if (!/1\d{10}/.test(formData.teamPhone)) {
      alert('团队队长手机号不规范')
      return false
    }

    let err = ''
    formData.teamInfo.forEach(item => {
      if (!item.name) {
        err = '请填写队长姓名'
      }
      if (!item.gender) {
        err = '请填写队长性别'
      }
      if (!item.wechat) {
        err = '请填写队长微信'
      }
      if (!item.email) {
        err = '请填写队长邮箱'
      }
      if (!item.school) {
        err = '请填写队长高校名称'
      }
      if (!item.major) {
        err = '请填写队长专业名称'
      }
      if (!item.grade) {
        err = '请填写队长年级'
      }
    })
    if (err) {
      alert(err)
      return false
    }

    formData.teacher.forEach(item => {
      if (!item.name) {
        err = '请填写老师姓名'
      }
      if (!item.gender) {
        err = '请填写老师性别'
      }
      if (!item.phone) {
        err = '请填写老师手机号'
      }
      if (!item.email) {
        err = '请填写老师邮箱'
      }
      if (!item.school) {
        err = '请填写老师高校名称'
      }
      if (!item.job) {
        err = '请填写老师职务名称'
      }
    })

    if (err) {
      alert(err)
      return false
    }

    formData.teamMember.forEach(item => {
      if (!item.name) {
        err = '请填写团队成员姓名'
      }
      if (!item.gender) {
        err = '请填写团队成员性别'
      }
      if (!item.phone) {
        err = '请填写团队成员手机号'
      }
      if (!item.email) {
        err = '请填写团队成员邮箱'
      }
      if (!item.school) {
        err = '请填写团队成员高校名称'
      }
      if (!item.major) {
        err = '请填写团队成员专业名称'
      }
      if (!item.grade) {
        err = '请填写团队成员年级'
      }
    })

    if (err) {
      alert(err)
      return false
    }
    return true
  }
</script>

<template>
  <div class="bg-blue-100 h-16"></div>

  <div class="bg-white p-4">
    <div class="py-4 text-center text-sky-500 text-2xl">2022-2023第十八届“花旗杯”金融创新应用大赛报名表</div>
    <div class="border-b pb-4">
      亲爱的同学们，你们好！欢迎大家报名本次2022-2023第十八届“花旗杯”金融创新应用大赛活动！本报名表所填信息必须真实，请同学们务必认真填写，感谢大家的支持与配合！
      <span class="text-red-500">（填写报名表的过程中如遇任何问题，请添加工作人员微信 [微信号：EFG-GCC]）</span>
    </div>

    <div class="py-4 space-y-8">
      <section>
        <div>
          1.请确认是否同意本次大赛出于花旗杯金融创新应用大赛之目的向花旗杯大赛组委会披露相关个人信息并同意花旗杯大赛组委会出于花旗杯金融创新应用大赛之目的进一步处理相关个人信息
          <div class="py-2 text-red-500 text-sm font-bold">注意：如您未确认及授权，我们将视作无效报名！（所收集涉及到的个人信息仅限大赛方用于本次大赛报名及联络等相关事宜，不会对外公开）</div>
        </div>
        <div class="flex flex-col">
          <label class="text-slate-500 flex items-center  gap-2 cursor-pointer hover:bg-slate-50 p-2"><input class="form-radio form-radio-user" type="radio"
              v-model="formData.agree" value="1" />
            是</label>
          <label class="text-slate-500 flex items-center  gap-2 cursor-pointer hover:bg-slate-50 p-2"><input class="form-radio form-radio-user" type="radio"
              v-model="formData.agree" value="0" />
            否</label>
        </div>
      </section>

      <section>
        <div>
          2.你们团队想要参加的是：
        </div>
        <div class="flex flex-col">
          <label class="text-slate-500 flex items-center gap-2 cursor-pointer hover:bg-slate-50 p-2"><input class="form-radio form-radio-user" type="radio" v-model="formData.type"
              value="1" /> 花旗挑战</label>
          <label class="text-slate-500 flex items-center gap-2 cursor-pointer hover:bg-slate-50 p-2"><input class="form-radio form-radio-user" type="radio" v-model="formData.type"
              value="0" /> 自选赛道</label>
        </div>
      </section>

      <section v-if="formData.type != '' && formData.type != '0'">
        <div>
          3.你们团队想要参加下列那种（花旗挑战）：
        </div>
        <div class="flex flex-col">
          <label class="text-slate-500 flex items-center gap-2 cursor-pointer hover:bg-slate-50 p-2"><input class="form-radio form-radio-user" type="radio"
              v-model="formData.teamType" value="1" />
            ESG（环境、社会与公司治理）</label>
          <label class="text-slate-500 flex items-center gap-2 cursor-pointer hover:bg-slate-50 p-2"><input class="form-radio form-radio-user" type="radio"
              v-model="formData.teamType" value="0" /> Virtual
            Economy（虚拟经济）</label>
        </div>
      </section>

      <section v-if="formData.type !='' && formData.type != '0' &&  formData.teamType == '1'">
        <div>
          4.你们团队的项目名称是【花旗挑战-ESG（环境、社会与公司治理）】：
        </div>
        <div class="flex flex-col mt-2">
          <input type="text" v-model="formData.esgName" class="form-input form-input-user">
        </div>
      </section>

      <section v-if="formData.type !='' && formData.type != '0' && formData.teamType == '0'">
        <div>
          5.你们团队的项目名称是【花旗挑战-Virtual Economy（虚拟经济）】：
        </div>
        <div class="flex flex-col mt-2">
          <input type="text" v-model="formData.vEName" class="form-input form-input-user">
        </div>
      </section>

      <section v-if="formData.type == '0'">
        <div>
          6.你们团队的项目名称是（自选赛道）：
        </div>
        <div class="flex flex-col mt-2">
          <input type="text" v-model="formData.projectName" class="form-input form-input-user">
        </div>
      </section>

      <section>
        <div>
          7.你们的团队名称是：
        </div>
        <div class="flex flex-col mt-2">
          <input type="text" v-model="formData.teamName" class="form-input form-input-user">
        </div>
      </section>

      <section>
        <div>
          8.你们团队队长的手机号码是：
          <div class="text-slate-500 text-sm">
            该手机号将作为后续修改团队名单的验证号码，请大家慎重填写！
            <b class="text-red-500">（注意：这里必须填写中国大陆手机号！！！）</b>
          </div>
        </div>
        <div class="flex flex-col mt-2">
          <input type="text" v-model="formData.teamPhone" class="form-input form-input-user w-1/2">
        </div>
      </section>

      <section>
        <div>
          9.团队队长信息
        </div>
        <div class="flex flex-col mt-2 overflow-auto">
          <table class="table-scroll">
            <thead class="thead">
              <tr>
                <th class="w-12"></th>
                <th>姓名</th>
                <th>性别</th>
                <th>微信号</th>
                <th>邮箱地址</th>
                <th>高校名称</th>
                <th>专业名称</th>
                <th>年级（如: 2022级大一）</th>
              </tr>
            </thead>
            <tbody class="tbody">
              <tr v-for="d, i in formData.teamInfo" :key="i">
                <td class="bg-slate-100 w-12">队长</td>
                <td v-for="m, n in d" :key="n">
                  <input type="text" class="px-4 py-2 w-full border-none outline-none focus:ring-1 focus:ring-blue-500 transition" v-model="formData.teamInfo[i][n]" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <section>
        <div>
          10.指导老师信息
          <div class="text-sm text-slate-500">（每个团队可根据自己的需求选择是否邀请指导老师，但每个团队至多2名指导老师）</div>

        </div>
        <div class="flex flex-col mt-2 overflow-auto">
          <table class="table-scroll">
            <thead class="thead">
              <tr>
                <th class="w-12"></th>
                <th>姓名</th>
                <th>性别</th>
                <th>手机号</th>
                <th>邮箱地址</th>
                <th>在职高校名称</th>
                <th>职务名称</th>
              </tr>
            </thead>
            <tbody class="tbody">
              <tr v-for="d, i in formData.teacher" :key="i">
                <td class="bg-slate-100 w-12 flex items-center justify-center">
                  <span class="border w-full cursor-pointer bg-red-500 text-white hover:bg-red-400 rounded" v-if="i > 0" @click="formData.teacher.splice(i, 1)">－</span>
                  <span v-else>{{i+1}}</span>
                </td>
                <td v-for="m, n in d" :key="n">
                  <input type="text" class="px-4 py-2 w-full border-none outline-none focus:ring-1 focus:ring-blue-500 transition" v-model="formData.teacher[i][n]" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="flex items-center justify-center mt-4" v-if="formData.teacher.length < 2">
          <span class="border p-2 px-8 text-slate-500 flex items-center gap-2 cursor-pointer hover:bg-slate-100 rounded" @click="addTeacher">
            <span class="bg-blue-500 w-5 h-5 flex items-center justify-center text-white rounded-full ">＋</span>
            增加
          </span>
        </div>
      </section>

      <section>
        <div>
          11.团队队员信息
          <div class="text-sm text-slate-500">（每个团队除队长外，包含至少2名队员）</div>
        </div>
        <div class="flex flex-col mt-2 overflow-auto">
          <table class="table-scroll">
            <thead class="thead">
              <tr>
                <th class="w-12"></th>
                <th>姓名</th>
                <th>性别</th>
                <th>手机号</th>
                <th>邮箱地址</th>
                <th>高校名称</th>
                <th>专业名称</th>
                <th>年级（如: 2022级大一）</th>
              </tr>
            </thead>
            <tbody class="tbody">
              <tr v-for="d, i in formData.teamMember" :key="i">
                <td class="bg-slate-100 w-12 flex items-center justify-center">
                  <span class="border w-full cursor-pointer bg-red-500 text-white hover:bg-red-400 rounded" v-if="i > 1 && i == formData.teamMember.length-1"
                    @click="formData.teamMember.splice(i, 1)">－</span>
                  <span v-else>{{i+1}}</span>
                </td>
                <td v-for="m, n in d" :key="n">
                  <input type="text" class="px-4 py-2 w-full border-none outline-none focus:ring-1 focus:ring-blue-500 transition" v-model="formData.teamMember[i][n]" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="flex items-center justify-center mt-4" v-if="formData.teamMember.length >= 2">
          <span class="border p-2 px-8 text-slate-500 flex items-center gap-2 cursor-pointer hover:bg-slate-100 rounded" @click="addTamMember">
            <span class="bg-blue-500 w-5 h-5 flex items-center justify-center text-white rounded-full ">＋</span>
            增加
          </span>
        </div>
      </section>

      <div class="text-center pt-20 pb-8 sticky bottom-0">
        <button class="m-auto py-3 px-20 rounded bg-blue-500 hover:bg-blue-600 transition text-white" @click="submit">提交</button>
      </div>
    </div>


    <!-- 真正 POST 提交 -->
    <form ref="formRef" class="flex items-center justify-center mt-12" method="post" :action="formAction">
      <input class="border" type="hidden" name="_csrf_token" :value="csrf_token">
      <input name="formData" type="hidden" class="w-full border" :value="JSON.stringify(rawForm)">
      <!-- <input type="submit" value="提交" class="w-auto py-3 px-20 rounded bg-blue-500 text-white" /> -->
    </form>
  </div>


  <!-- 测试信息，打包后删除 -->
  <div class="bg-black/50 px-4 text-white mt-4 sticky bottom-0 hidden">
    <div class="font-medium">formAction: {{ formAction }}</div>
    <div class="font-medium">csrf_token: {{ csrf_token }}</div>
    <div class="bg-red-400/50 p-2">
      formData
      <div class="p-2 border border-red-300">
        {{ formData }}
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .form-radio-user {
    @apply border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-offset-0 focus:ring-blue-200 focus:ring-opacity-50;
  }

  .form-input-user {
    @apply border-gray-300 shadow-sm focus:border-blue-300 focus:ring focus:ring-offset-0 focus:ring-blue-200 focus:ring-opacity-50 rounded transition;
  }

  .table-scroll {
    @apply text-sm text-center text-slate-500;

    .thead {
      @apply bg-slate-100;
    }

    .tbody {
      @apply bg-white;
    }

    th,
    td {
      @apply border;

      &:first-child {
        @apply sticky left-0 whitespace-nowrap p-2;
      }
    }

    th {
      @apply text-slate-500 whitespace-nowrap py-2 px-6;
    }

    td {}

  }
</style>